package com.wyzz.hr.action;

import java.util.*;
import javax.servlet.http.HttpSession;

import com.wyzz.hr.base.BaseAction;
import com.wyzz.hr.base.DWRUtil;
import com.wyzz.hr.bo.IEmailsendBO;
import com.wyzz.hr.bo.IEmailtemplateBO;
import com.wyzz.hr.bo.IEmployeeBo;
import com.wyzz.hr.bo.UserBo;
import com.wyzz.hr.bo.impl.EmpDistinctNo;
import com.wyzz.hr.pojo.Emailsend;
import com.wyzz.hr.pojo.Emailtemplate;
import com.wyzz.hr.pojo.Employee;
import com.wyzz.hr.pojo.Userinfo;
import com.wyzz.hr.spring.SpringBeanFactory;

public class ModifyUserPassword extends BaseAction {

	public ModifyUserPassword() {
	}

	public String updateUserPassword(String userId, String password,
			String userName, String flag, HttpSession session) {
		String flt = DWRUtil.checkAuth("userList", "execute");
		if ("error".equalsIgnoreCase(flt))
			return "noauth";
		UserBo userService = (UserBo) SpringBeanFactory.getBean("userService");
		Userinfo user = userService.getUserById(userId);
		if (user == null)
			return "nouser";
		if ("demo".equals(session.getAttribute("loginModel"))
				&& userId.length() >= 5
				&& "TYHRM".equalsIgnoreCase(EmpDistinctNo.getEmpDistinctNo(
						userId).substring(0, 5)))
			return "demo";
		if (userName.trim().length() > 0 && password.trim().length() > 0) {
			Employee currentEmployee = ((Userinfo) session
					.getAttribute("userinfo")).getEmployee();
			String createrId = currentEmployee.getId();
			boolean updateResult = true;
			if (userName.equals(user.getUiUsername())) {
				updateResult = userService.updatePasswordBy(userId, null,
						password, createrId);
			} else {
				Userinfo userInfo = userService.getUserByName(userName);
				if (userInfo != null)
					return "exist";
				updateResult = userService.updatePasswordBy(userId, userName,
						password, createrId);
			}
			if (!updateResult)
				return "error";
			if ("1".equals(flag)) {
				IEmployeeBo empBo = (IEmployeeBo) getBean("empBo");
				Employee receiver = empBo.loadEmp(userId, null);
				Map paramUserEmail = new HashMap();
				paramUserEmail.put("SENDER", currentEmployee);
				paramUserEmail.put("APPLIER", receiver);
				paramUserEmail.put("USERNAME", userName);
				paramUserEmail.put("PASSWORD", password);
				paramUserEmail.put("URL", "configuration/login.jsp");
				IEmailtemplateBO templateBo = (IEmailtemplateBO) SpringBeanFactory
						.getBean("emailtemplateBO");
				Emailtemplate template = templateBo
						.getEmailTemplateByNo("NewUserPassword");
				IEmailsendBO emailsendBo = (IEmailsendBO) SpringBeanFactory
						.getBean("emailsendBO");
				Emailsend send = emailsendBo.getEmailUser(paramUserEmail,
						template);
				List esList = new ArrayList();
				esList.add(send);
				emailsendBo.sendEmailsMain(esList);
			}
			return "success";
		} else {
			return "error";
		}
	}

	private static final long serialVersionUID = 0xc53a77b0ae03eebfL;
}
